package manage.modules.upload.service.impl;

import java.io.IOException;

import manage.commons.Constants;
import manage.commons.utils.UploadUtils;
import manage.modules.upload.model.SingleFile;
import manage.modules.upload.service.UploadFileService;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

public class UploadFileServiceImpl implements UploadFileService {

	private String filePath = "";

	public void setFilePath(String filePath) {
		filePath = StringUtils.stripEnd(filePath, Constants.SEPARATE);
		filePath = StringUtils.stripEnd(filePath, Constants.SEPARATE);
		this.filePath = filePath;
	}

	private String getPathPrifex(String filePath, Long workerId) {
		return filePath + Constants.SEPARATE + workerId + Constants.SEPARATE;
	}

	@Override
	public String getFilePath(String fileName, Long workerId) {
		return getPathPrifex(filePath, workerId) + fileName;
	}

	@Override
	public String upload(SingleFile singleFile, Long workerId)
			throws IOException {
		String folder = getPathPrifex(filePath, workerId);
		return UploadUtils.upload(folder,
				FileUtils.readFileToByteArray(singleFile.getUpload()),
				singleFile.getExts());
	}

	@Override
	public void delete(Long workerId, String fileName) {
		String[] cc = fileName.split("-");
		if (cc.length < 2) {
			return;
		}
		if (cc[1].length() < 2) {
			return;
		}
		String deletFileName = getPathPrifex(filePath, workerId) + cc[0]
				+ Constants.SEPARATE + cc[1];
		UploadUtils.delete(deletFileName);
	}

}
